package com.fishy.chat.codec;

import cn.hutool.json.JSONUtil;
import com.fishy.chat.model.entity.Message;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * WebSocket消息编码器
 *
 * @author sunn
 */
@Component
@ChannelHandler.Sharable
public class WebSocketMessageEncoder extends MessageToMessageEncoder<Message> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Message message, List<Object> out) {
        String msgStr = JSONUtil.toJsonStr(message);
        TextWebSocketFrame frame = new TextWebSocketFrame(msgStr);
        out.add(frame);
    }
}
